package com.nb.system.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Condition;
import org.nutz.dao.Dao;
import org.nutz.dao.sql.Criteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nb.common.service.BaseService;
import com.nb.system.NewPager;
import com.nb.system.model.User;
import com.nb.system.model.UserRole;

/**
 * 人大代表信息
 * 模板自动生成   for FreeUI
 * @author mefly
 *
 */

@Service
public class UserService extends BaseService {

	@Autowired
	private Dao dao;

	public void create() {
		dao.create(User.class, false);
	}
	public int delete(Integer id) {
		return dao.delete(User.class,id);
	}

	public User insert(User record) {
		return dao.insert(record);
	}
	
	//删除子表
	public void deleteUserRole(int id) {
		User user = dao.fetch(User.class, id);
		dao.clearLinks(user, "userRoles");
	}

	//插入子表信息
	public void insertUserRole(int[] roles,long id) {
		User user = new User();
		user.setId(id);
		List<UserRole> userRoles = new ArrayList<UserRole>();
		for (int roleid : roles) {
			userRoles.add(new UserRole(id,roleid));
		}
		user.setUserRoles(userRoles);
		dao.insertLinks(user,"userRoles");
		
	}

	public User fetchUserRoles(Integer id) {
		return dao.fetchLinks(dao.fetch(User.class, id), "userRoles");
	}
	
	public User fetch(Integer id) {
		return dao.fetch(User.class,id);
	}

	public List<User> query(Condition c){
		return dao.query(User.class,c, null);
	}

	public int update(User record) {
		return dao.update(record);
	}

	public int updateIgnoreNull(User record) {
		return dao.updateIgnoreNull(record);
	}
	
	public Map<String,Object> queryPage(NewPager page){
		Criteria cri = getCriteriaFromPage(page);
		
	    List<User> list = dao.query(User.class, cri, page);
	    page.setRecordCount(dao.count(User.class, cri));
	    
	    Map<String,Object> map = new HashMap<String,Object>();
		map.put("Total", page.getRecordCount());
		map.put("Rows", list);
	    return map;
	}
	
}
